package services
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class AlbumSearch extends HTTPService
	{
		public function AlbumSearch(rootURL:String=null, destination:String=null)
		{
			super(rootURL, destination);
			url="http://ws.audioscrobbler.com/2.0";
			method="POST";						
		}
		
		//TODO: externalize api key
		private function getParams():Object {
			var o:Object = new Object();
			o["method"] = "album.search";
			o["album"] = escape(_search);
			o["api_key"] = "0dfd0495ea40be5d5d32963ad6222bd4";
			o["limit"] = _limit.toString();
			o["page"] = _page.toString();
			return o;			
		}
		
		// since the getResult hook isn't used by the AbstractInvoker implementation of
		// sdk 3.2 we need to use an own bindable instead of lastResult!!!
		[Bindable]
		public var searchResult:ArrayCollection = null;
				
		private var _search:String;
		private var _limit:int; 
		private var _page:int;
		
		// maximum for limit == 30 == default
		public function searchAlbums(search:String,limit:int=30,page:int=0):void {
			if (search == null || search == "") {
				searchResult = null;
			}								
			else {
				_limit = limit;
				_page = page;
				_search = search;
				var token:AsyncToken = send(getParams());				
				token.addResponder(new Responder(resultHandler,faultHandler));
			}
		}
						
		public function resultHandler(e:ResultEvent):void {
			searchResult = extractValidResults(e.result);
		}
		
		public function faultHandler(e:Event):void {
			searchResult = null;
			trace("[fault] e="+e);
		}
								
		private function extractValidResults(result:Object):ArrayCollection {
			if (result == null || result.lfm.results.albummatches == null) return null;
			
			var tmp:ArrayCollection = new ArrayCollection();
				
			for each(var item:Object in result.lfm.results.albummatches.album) {
				var imgurl:String = item.image[2].value;
				var artist:String = item.artist;
				var album:String = item.name;
				
				if (imgurl != null && imgurl != "" &&
					artist != null && artist != "" &&
					album  != null && album  != "") 
				{
					tmp.addItem(new AlbumVO(artist,album,imgurl));
				}
			}
			return tmp;	
		}
    	
	}
}